<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车 - 水果超市</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <div id="app" v-cloak>
    <!-- 页面头部 -->
    <div class="header">
      <div class="container clearfix">
        <h1>🛒 购物车</h1>
        <div class="header-actions">
          <a href="/index.html" class="btn btn-default">继续购物</a>
          <a href="/admin.html" class="btn btn-default">⚙️ 管理后台</a>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        加载中...
      </div>

      <!-- 空购物车 -->
      <div v-else-if="!cart || !cart.items || cart.items.length === 0" class="empty-state">
        <div class="empty-state-icon">🛒</div>
        <div class="empty-state-text">购物车是空的</div>
        <a href="/index.html" class="btn btn-primary">去购物</a>
      </div>

      <!-- 购物车内容 -->
      <div v-else>
        <!-- 购物车商品网格 -->
        <div class="cart-header">
          <h3>购物车商品 ({{ cart.items.length }} 件)</h3>
        </div>
        
        <div class="product-grid">
          <div v-for="item in cart.items" :key="item.id" 
               class="product-card cart-product-card"
               :class="{ 'unavailable-item': item.available === false }">
            <!-- 商品图标 -->
            <div class="product-image" :style="{ opacity: item.available === false ? 0.5 : 1 }">
              {{ getProductEmoji(item.productName) }}
            </div>

            <!-- 商品信息 -->
            <div class="product-name">{{ item.productName }}</div>
            
            <!-- 不可用提示 -->
            <div v-if="item.available === false" class="text-danger" style="font-size: 12px; font-weight: bold;">
              ⚠️ {{ item.unavailableReason || '该商品已下架' }}
            </div>
            <div v-else class="text-muted" style="font-size: 12px;">购物车商品</div>

            <!-- 价格信息 -->
            <div class="product-price" v-if="item.available !== false && item.unitPrice">
              <span>{{ formatMoney(item.unitPrice.amount) }}/{{ item.quantity.unitName || item.quantity.unit }}</span>
              <span v-if="item.originalPrice && item.originalPrice.amount !== item.unitPrice.amount" 
                    class="original-price" style="margin-left: 8px; text-decoration: line-through; color: #999;">
                {{ formatMoney(item.originalPrice.amount) }}/{{ item.quantity.unitName || item.quantity.unit }}
              </span>
            </div>
            <div class="product-price text-muted" v-else>
              暂无价格
            </div>

            <!-- 数量调整 -->
            <div class="product-actions">
              <div class="form-group">
                <div class="form-inline" style="justify-content: center;">
                  <input 
                    type="number" 
                    class="form-control" 
                    style="width: 80px;"
                    v-model.number="item.quantity.value"
                    @change="updateQuantity(item)"
                    :disabled="item.available === false"
                    :min="item.available === false ? 0 : 1"
                    step="1"
                  >
                  <span style="margin-left: 5px; font-size: 12px;">{{ item.quantity.unitName || item.quantity.unit }}</span>
                </div>
              </div>
              
              <!-- 小计显示 -->
              <div class="cart-subtotal" v-if="item.available !== false && item.subtotal">
                <strong>小计：{{ formatMoney(item.subtotal.amount) }}</strong>
              </div>
              <div class="cart-subtotal text-muted" v-else>
                <strong>小计：不可用</strong>
              </div>
              
              <!-- 操作按钮 -->
              <button class="btn btn-danger btn-sm" @click="removeItem(item)" style="width: 100%;">
                删除商品
              </button>
            </div>
          </div>
        </div>

        <!-- 订单汇总 -->
        <div class="card">
          <div class="card-header">订单汇总</div>
          <div class="order-summary">
            <!-- 总价（商品原价） -->
            <div class="summary-row">
              <span>总价：</span>
              <span v-if="cart.subtotal">{{ formatMoney(cart.subtotal.amount) }}</span>
              <span v-else class="text-muted">暂无</span>
            </div>

            <!-- 单品折扣（新增）-->
            <div class="summary-row discount-detail" v-if="cart.itemDiscount && cart.itemDiscount.amount > 0">
              <span style="padding-left: 20px; color: #909399;">└ 单品折扣：</span>
              <span class="text-success">-{{ formatMoney(cart.itemDiscount.amount) }}</span>
            </div>

            <!-- 满减优惠（新增）-->
            <div class="summary-row discount-detail" v-if="cart.thresholdDiscount && cart.thresholdDiscount.amount > 0">
              <span style="padding-left: 20px; color: #909399;">└ 满减优惠：</span>
              <span class="text-success">-{{ formatMoney(cart.thresholdDiscount.amount) }}</span>
            </div>

            <!-- 优惠合计 -->
            <div class="summary-row" v-if="cart.discount && cart.discount.amount > 0" style="font-weight: bold;">
              <span>优惠合计：</span>
              <span class="text-success">-{{ formatMoney(cart.discount.amount) }}</span>
            </div>
            <div class="summary-row" v-else>
              <span>优惠合计：</span>
              <span class="text-muted">0.00</span>
            </div>

            <!-- 分割线 -->
            <div class="divider"></div>

            <!-- 应付金额 -->
            <div class="summary-row total">
              <span>应付金额：</span>
              <span v-if="cart.total" class="total-amount">{{ formatMoney(cart.total.amount) }}</span>
              <span v-else class="text-muted">暂无</span>
            </div>

            <!-- 促销规则说明 -->
            <div v-if="cart.appliedPromotions && cart.appliedPromotions.length > 0" class="mt-20">
              <div style="font-size: 12px; color: #909399; margin-bottom: 10px;">已应用优惠：</div>
              <div v-for="promo in cart.appliedPromotions" :key="promo.id">
                <span class="badge badge-danger">{{ promo.name }}</span>
              </div>
            </div>

            <!-- 操作按钮（右对齐，贴齐金额列），并适度缩小按钮视觉体量） -->
            <div class="mt-20" style="display: flex; justify-content: flex-end; gap: 12px;">
              <button class="btn btn-danger" @click="clearCart" 
                      style="min-width: 140px; padding: 10px 14px; font-size: 14px;">
                清空购物车
              </button>
              <button class="btn btn-success" @click="goCheckout" 
                      style="min-width: 140px; padding: 10px 14px; font-size: 14px;">
                去结算
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 引入依赖 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="/js/config.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/api.js"></script>

  <!-- 页面脚本 -->
  <script>
    const { createApp } = Vue;

    createApp({
      data() {
        return {
          loading: false,
          cart: null,
        };
      },
      
      mounted() {
        this.loadCart();
      },
      
      methods: {
        /**
         * 加载购物车
         */
        async loadCart() {
          this.loading = true;
          try {
            // 优先使用本地存储的购物车ID
            let cartId = storage.get('cartId');
            
            if (!cartId) {
              // 如果本地没有，通过用户ID获取
              const userId = CONFIG.DEMO_USER_ID;
              const result = await API.getActiveCartByUser(userId);
              
              if (result.data && result.data.id) {
                cartId = result.data.id;
                storage.set('cartId', cartId);
              } else {
                // 如果不存在，创建新购物车
                const cartResult = await API.getOrCreateCart();
                cartId = cartResult.data.id;
                storage.set('cartId', cartId);
              }
            }
            
            // 获取购物车详情
            const result = await API.getCart(cartId);
            this.cart = result.data || { items: [] };
            console.log('购物车加载成功：', this.cart);
          } catch (error) {
            console.error('加载购物车失败：', error);
            this.cart = { items: [] };
          } finally {
            this.loading = false;
          }
        },
        
        /**
         * 更新商品数量
         */
        async updateQuantity(item) {
          // 如果商品不可用，禁止更新
          if (item.available === false) {
            showError(new Error('该商品已下架，无法修改数量'));
            this.loadCart(); // 重新加载恢复原值
            return;
          }
          
          // 验证数量
          if (!isPositiveNumber(item.quantity.value)) {
            showError(new Error('请输入有效的数量'));
            this.loadCart(); // 重新加载恢复原值
            return;
          }
          
          try {
            const cartId = storage.get('cartId');
            if (!cartId) {
              showError(new Error('购物车ID不存在'));
              return;
            }
            
            await API.updateCartItem(cartId, item.id, {
              quantity: item.quantity.value
            });
            
            // 重新加载购物车以更新价格
            await this.loadCart();
            showSuccess('数量已更新');
          } catch (error) {
            showError(error);
            this.loadCart(); // 重新加载恢复原值
          }
        },
        
        /**
         * 删除商品
         */
        async removeItem(item) {
          if (!confirm(`确定要删除 ${item.productName} 吗？`)) {
            return;
          }
          
          try {
            const cartId = storage.get('cartId');
            if (!cartId) {
              showError(new Error('购物车ID不存在'));
              return;
            }
            
            await API.deleteCartItem(cartId, item.id);
            await this.loadCart();
            showSuccess('商品已删除');
          } catch (error) {
            showError(error);
          }
        },
        
        /**
         * 清空购物车
         */
        async clearCart() {
          if (!confirm('确定要清空购物车吗？')) {
            return;
          }
          
          try {
            const cartId = storage.get('cartId');
            if (!cartId) {
              showError(new Error('购物车ID不存在'));
              return;
            }
            
            await API.clearCart(cartId);
            this.cart = { items: [] };
            showSuccess('购物车已清空');
          } catch (error) {
            showError(error);
          }
        },
        
        /**
         * 去结算
         */
        goCheckout() {
          // TODO: 订单功能正在开发中
          alert('🚧 订单结算功能正在建设中，敬请期待！');
          // const cartId = storage.get('cartId');
          // if (!cartId) {
          //   showError(new Error('购物车ID不存在'));
          //   return;
          // }
          // window.location.href = `/checkout.html?cartId=${cartId}`;
        },
        
        /**
         * 根据商品名获取表情符号
         */
        getProductEmoji(productName) {
          if (productName.includes('苹果')) return '🍎';
          if (productName.includes('香蕉')) return '🍌';
          if (productName.includes('橙')) return '🍊';
          if (productName.includes('葡萄')) return '🍇';
          if (productName.includes('草莓')) return '🍓';
          if (productName.includes('西瓜')) return '🍉';
          if (productName.includes('桃')) return '🍑';
          if (productName.includes('梨')) return '🍐';
          return '🍎';
        },
        
        /**
         * 格式化金额
         */
        formatMoney(amount) {
          return formatMoney(amount);
        },
      }
    }).mount('#app');
  </script>
</body>
</html>

